package org.ourgrid.broker.business.schedulerdata.executor;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.broker.business.dao.BrokerDAOFactory;
import org.ourgrid.broker.business.dao.JobDAO;
import org.ourgrid.broker.business.schedulerdata.SchedulerData;
import org.ourgrid.broker.response.RequestWorkersResponseTO;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.spec.job.JobSpec;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class RequestWorkersExecutor extends AbstractSchedulerDataExecutor {
	
	/**
	 * <REQUEST_WORKERS peerID='String' requestID='long' jobID='int' requiredWorkers='int'
	 *          maxFails='int' maxReplicas='int'/>
	 */
	public List<IResponseTO> execute(SchedulerData command) {
		
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		Document logDocFile = super.getXMl(command.getXml());
		
		Element element = logDocFile.getDocumentElement();
		
		String pID = element.getAttribute("peerID");
		long requestID = Long.valueOf(element.getAttribute("requestID"));
		int jobID = Integer.valueOf(element.getAttribute("jobID"));
		int requiredWorkers = Integer.valueOf(element.getAttribute("requiredWorkers"));
		int maxFails = Integer.valueOf(element.getAttribute("maxFails"));
		int maxReplicas = Integer.valueOf(element.getAttribute("maxReplicas"));
	
		if (pID != null) {
			JobDAO jobDAO = BrokerDAOFactory.getInstance().getJobDAO();
			JobSpec jobSpec = jobDAO.getJobSpec(jobID);
			
			RequestWorkersResponseTO to = new RequestWorkersResponseTO();
			to.setJobID(jobID);
			to.setMaxFails(maxFails);
			to.setMaxReplicas(maxReplicas);
			to.setRequestID(requestID);
			to.setRequiredWorkers(requiredWorkers);
			to.setPeerAddress(getAddress(pID));
			to.setJobSpec(jobSpec);
			
			responses.add(to);
			
			jobDAO.addJobRequest(jobID, requestID);
		}
		return responses;
	}
}
